package com.aia.prm.web.ria.app.ui.config;

import java.util.Arrays;
import java.util.List;

import org.apache.log4j.Logger;

import com.aia.prm.BeanFactory;
import com.aia.prm.web.ria.app.PrmApplication;
import com.cfh.domain.Config;
import com.cfh.persistence.dao.ConfigDAO;
import com.vaadin.data.Item;
import com.vaadin.data.util.BeanItem;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.TextField;

@SuppressWarnings("serial")
class ConfigForm extends Form implements ClickListener {
	private static final Logger logger = Logger.getLogger(ConfigForm.class);
	private Button save = new Button("保存", (ClickListener) this);
	private Button cancel = new Button("取消", (ClickListener) this);
	private Button edit = new Button("编辑", (ClickListener) this);
	private boolean newContactMode = false;
	private Config newConfig = null;
	ConfigView view = null;
	public ConfigForm(ConfigView aview) {
		setIcons();
		view = aview;
		getLayout().setMargin(true);
		setSizeFull();
		setWriteThrough(false);
		HorizontalLayout footer = new HorizontalLayout();
		footer.setSpacing(true);
		footer.addComponent(save);
		footer.addComponent(cancel);
		footer.addComponent(edit);
		footer.setVisible(false);
		setFooter(footer);
		setFormFieldFactory(new DefaultFieldFactory() {
			public Field createField(Item item, Object propertyId, Component uiContext) {
				Field field = super.createField(item, propertyId, uiContext);
				if (field instanceof TextField) {
					((TextField) field).setNullRepresentation("");
					((TextField) field).setNullSettingAllowed(true);
				}
				if (ConfigContainer.FIELD_NAME_MAP.containsKey(propertyId)) {
					field.setCaption(ConfigContainer.FIELD_NAME_MAP.get(propertyId));
				}

				return field;
			}
		});
		
	}
	
	private void setIcons() {
		edit.setIcon(new ThemeResource("icons/edit.png"));
		save.setIcon(new ThemeResource("icons/accept.png"));
		cancel.setIcon(new ThemeResource("icons/back.png"));
		setIcon(new ThemeResource("icons/comment_edit.png"));
	}

	public void buttonClick(ClickEvent event) {
        Button source = event.getButton();

        if (source == save) {
            /* If the given input is not valid there is no point in continuing */
            if (!isValid()) {
                return;
            }
            logger.debug("ready to Save");
            commit();
            ConfigDAO configDAO = (ConfigDAO) BeanFactory.get().getBean("configDAO");
            BeanItem item = (BeanItem) this.getItemDataSource();
            Config config  = (Config) item.getBean();
            configDAO.updateByPrimaryKey(config);
            
            PrmApplication.getInstance().getMainWindow().showNotification("成功");
            view.load();
            
            if (newContactMode) {
                /* We need to add the new person to the container */
                //Item addedItem = app.getDataSource().addItem(newPerson);
            	Item addedItem = view.configContainer.addItem(newConfig);
                /*
                 * We must update the form to use the Item from our datasource
                 * as we are now in edit mode (no longer in add mode)
                 */
                setItemDataSource(addedItem);

                newContactMode = false;
            }
            setReadOnly(true);
        } else if (source == cancel) {
            if (newContactMode) {
                newContactMode = false;
                /* Clear the form and make it invisible */
                setItemDataSource(null);
            } else {
                discard();
            }
            setReadOnly(true);
        } else if (source == edit) {
            setReadOnly(false);
        }
    }

	@Override
	public void setItemDataSource(Item newDataSource) {
		newContactMode = false;

		if (newDataSource != null) {
			super.setItemDataSource(newDataSource);
			 List<Object> orderedProperties = Arrays
			 .asList(ConfigContainer.NATURAL_COL_ORDER);
			super.setItemDataSource(newDataSource, orderedProperties);

			setReadOnly(true);
			getFooter().setVisible(true);
		} else {
			super.setItemDataSource(null);
			getFooter().setVisible(false);
		}
	}
	
    @Override
    public void setReadOnly(boolean readOnly) {
        super.setReadOnly(readOnly);
        
        if (!newContactMode && getItemDataSource() != null) {
			setReadOnlyByFieldName("CFG_TYPE");
			setReadOnlyByFieldName("CFG_CODE");
			//setReadOnlyByFieldName("CFG_DESC");
		}
        
        save.setVisible(!readOnly);
        cancel.setVisible(!readOnly);
        edit.setVisible(readOnly);
    }
    
    private void setReadOnlyByFieldName(String string) {
		Field f = getField(string);
		if (f != null) {
			f.setReadOnly(true);
		} else {
			logger.warn("field is null:" + string);
		}

	}

    public void addObject() {
        // Create a temporary item for the form
    	newConfig = new Config();
        setItemDataSource(new BeanItem<Config>(newConfig));
        newContactMode = true;
        setReadOnly(false);
    }
}